package com.gzhryc.common;

import com.gzhryc.common.json.JsonTools;

import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * 不支持OpenJDK
 */
public class JavascriptTools {
	
	static ThreadLocal<ScriptEngine> localEngin = new ThreadLocal<ScriptEngine>();

	static ScriptEngineManager sem = new ScriptEngineManager();

	public static ScriptEngine getJsEngine() {
		ScriptEngine engine = localEngin.get();
		if(engine == null) {
			engine = sem.getEngineByName("javascript");
			localEngin.set(engine);
		}
		return engine;
	}
	
	public static Object compute(String script) {
		try {
			ScriptEngine engine = getJsEngine();
			return engine.eval(script);
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Object eval(String script) {
		try {
			ScriptEngine engine = getJsEngine();
			return engine.eval("(function(){"+script+"})();");
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Object eval(String script,Map<String,Object> map) {
		String params = "";
		if(map != null && map.size() > 0) {
			for(String name : map.keySet()) {
				Object obj = map.get(name);
				params = params + ","+name+" = " + JsonTools.toJson(obj);
			}
			params = "var "+params.substring(1)+";";
		}
		
		String temp = "(function(){"+params+script+"})();";
		try {
			ScriptEngine engine = getJsEngine();
			return engine.eval(temp);
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static <T> T eval(String script,Map<String,Object> map,Class<T> clazz) {
		Object obj = eval(script,map);
		if(Map.class.isInstance(obj)) {
			String json = JsonTools.toJson(obj);
			return JsonTools.fromJson(json, clazz);
		}
		return null;
	}
}
